<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-03-29
 * Time: 14:09
 */
ini_set("error_reporting","E_ALL & ~E_NOTICE");
if(phpversion() < '5.3.0') set_magic_quotes_runtime(0);
if(phpversion() < '5.2.0') exit('您的php版本过低，不能安装本软件，请升级到5.2.0或更高版本再安装，谢谢！');
define('INSTALL_MODULE',true);
define('HERE', dirname(__FILE__).DIRECTORY_SEPARATOR);
define('STEP_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR.'step'.DIRECTORY_SEPARATOR);
require('../constant.inc.php');
require('../Application/Common/Common/function.php');
$steps = include 'step.inc.php';
$step = trim($_REQUEST['step']) ? trim($_REQUEST['step']) : 1;

include '../lib/function/dir.func.php';
if(!check_is_installed()){
    echo "you already install this system <br> if you want to reinstall , please delete lock.lock file in root path";
    return;
}

switch($step){

    case '1':
        $license = file_get_contents(dir_path(HERE)."license.txt");
        include dir_path(HERE)."/step/step".$step.".tpl.php";
        break;

    case '2':
        $PHP_GD  = '';
        if(extension_loaded('gd')) {
            if(function_exists('imagepng')) $PHP_GD .= 'png';
            if(function_exists('imagejpeg')) $PHP_GD .= ' jpg';
            if(function_exists('imagegif')) $PHP_GD .= ' gif';
        }
        $PHP_JSON = '0';
        if(extension_loaded('json')) {
            if(function_exists('json_decode') && function_exists('json_encode')) $PHP_JSON = '1';
        }
        //新加fsockopen 函数判断,此函数影响安装后会员注册及登录操作。
        if(function_exists('fsockopen')) {
            $PHP_FSOCKOPEN = '1';
        }
        $PHP_DNS = preg_match("/^[0-9.]{7,15}$/", @gethostbyname('www.phpcms.cn')) ? 1 : 0;
        //是否满足phpcms安装需求
        $is_right = (phpversion() >= '5.2.0' && extension_loaded('mysqli') && $PHP_JSON && $PHP_GD && $PHP_FSOCKOPEN) ? 1 : 0;
        include HERE."/step/step".$step.".tpl.php";
        break;

    case '3'://选择安装模块

        include HERE."/step/step".$step.".tpl.php";
        break;

    case '4': //检测目录属性
        echo APP_BASE.'..';
        $chmod_file = 'chmod.txt';
        $files = file(HERE.$chmod_file);
        foreach($files as $_k => $file) {
            $file = str_replace('*','',$file);
            $file = trim($file);
            if(is_dir( APP_BASE.'..'.$file)) {
                $is_dir = '1';
                $cname = '目录';
                //继续检查子目录权限，新加函数
                $write_able = writable_check( APP_BASE.'../'.$file);
            } else {
                $is_dir = '0';
                $cname = '文件';
            }
            //新的判断
            if($is_dir =='0' && is_writable( APP_BASE.'../'.$file)) {
                $is_writable = 1;
            } elseif($is_dir =='1' && dir_writeable( APP_BASE.'../'.$file)){
                $is_writable = $write_able;
                if($is_writable=='0'){
                    $no_writablefile = 1;
                }
            }else{
                $is_writable = 0;
                $no_writablefile = 1;
            }

            $filesmod[$_k]['file'] = $file;
            $filesmod[$_k]['is_dir'] = $is_dir;
            $filesmod[$_k]['cname'] = $cname;
            $filesmod[$_k]['is_writable'] = $is_writable;
        }
        if(dir_writeable( APP_BASE.'..')) {
            $is_writable = 1;
        } else {
            $is_writable = 0;
        }
        $filesmod[$_k+1]['file'] = '网站根目录';
        $filesmod[$_k+1]['is_dir'] = '1';
        $filesmod[$_k+1]['cname'] = '目录';
        $filesmod[$_k+1]['is_writable'] = $is_writable;
        include HERE."/step/step".$step.".tpl.php";
        break;

    case '5': //配置帐号 （MYSQL帐号、管理员帐号、）
        $db_path = '../Application/Common/Conf/db_config.php';
        if(file_exists($db_path)){
            $db = require($db_path);
        }else{
            $db = require(HERE.'/db_config.php');
        }
        include HERE."/step/step".$step.".tpl.php";
        break;

    case '6': //安装详细过程
        extract($_POST);
        $testdata = $_POST['testdata'];
        include HERE."/step/step".$step.".tpl.php";
        break;

    case '7': //完成安装
        create_install_lock();
        include HERE."/step/step".$step.".tpl.php";
        break;

    case 'installmodule': //执行SQL
        extract($_POST);
        $GLOBALS['dbcharset'] = $dbcharset;
        $PHP_SELF = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['ORIG_PATH_INFO']);
        $rootpath = str_replace('\\','/',dirname($PHP_SELF));
        $rootpath = substr($rootpath,0,-7);
        $rootpath = strlen($rootpath)>1 ? $rootpath : "/";

        //取消安装时的模块选择，现在提取最精简的模块
        $cookie_pre = random(5, 'abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ').'_';
        $auth_key = random(20, '1294567890abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ');
        $sys_config = array('cookie_pre'=>$cookie_pre,
            'auth_key'=>$auth_key,
            'web_path'=>$rootpath,
            'errorlog'=>'0',
            'upload_url'=>'/upload/',
            'js_path'=>'P/ublic/js/',
            'css_path'=>'/Public/css/',
            'img_path'=>'/Public/images/',
        );

        $db_config = array(
            'DB_TYPE'=>'mysql',
            'DB_HOST'=>$dbhost,
            'DB_PORT'=>$dbport,
            'DB_USER'=>$dbuser,
            'DB_PWD'=>$dbpw,
            'DB_NAME'=>$dbname,
            'DB_PREFIX'=>$tablepre,
            'DB_CHARSET'=>$dbcharset,
        );
        set_config($sys_config,'static_config');
        set_config($db_config,'db_config');

        $link = mysqli_connect($dbhost, $dbuser, $dbpw, null, $dbport) or die ('Not connected : ' . mysqli_connect_error());
        $version = mysqli_get_server_info($link);

        if($version > '4.1' && $dbcharset) {
            mysqli_query($link, "SET NAMES '$dbcharset'");
        }

        if($version > '5.0') {
            mysqli_query($link, "SET sql_mode=''");
        }

        if(!@mysqli_select_db($link, $dbname)){
            @mysqli_query($link, "CREATE DATABASE $dbname");
            if(@mysqli_error($link)) {
                echo 1;exit;
            } else {
                mysqli_select_db($link, $dbname);
            }
        }
        $dbfile =  'ghost_cms.sql';
        if(file_exists(HERE."/sql/".$dbfile)) {
            $sql = file_get_contents(HERE."/sql/".$dbfile);
            _sql_execute($link,$sql,$tablepre);
            //创建网站创始人
            if($dbcharset=='gbk') $username = iconv('UTF-8','GBK',$username);
            $password_arr = password($password);
            $password = $password_arr['password'];
            $encrypt = $password_arr['encrypt'];
            $email = trim($email);
            _sql_execute($link,"INSERT INTO ".$tablepre."user (`id`,`username`,`password`,`realname`) VALUES ('1','$username','$password','$username')",$tablepre);

        } else {
            echo '2';//数据库文件不存在
        }
        echo $module;
        break;

    //数据库测试
    case 'dbtest':
        extract($_GET);
        $link = @mysqli_connect($dbhost, $dbuser, $dbpw,null,$dbport);
        if(!$link) {
            exit('2');
        }
        $server_info = mysqli_get_server_info($link);
        if($server_info < '4.0') exit('6');
        if(!mysqli_select_db($link,$dbname)) {
            if(!@mysqli_query($link,"CREATE DATABASE `$dbname`")) exit('3');
            mysqli_select_db($link,$dbname);
        }
        $tables = array();
        $query = mysqli_query($link,"SHOW TABLES FROM `$dbname`");
        while($r = mysqli_fetch_row($query)) {
            $tables[] = $r[0];
        }
        if($tables && in_array($tablepre.'module', $tables)) {
            exit('0');
        }
        else {
            exit('1');
        }
        break;


}

function random($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function dir_writeable($dir) {
    $writeable = 0;
    if(is_dir($dir)) {
        if($fp = @fopen("$dir/chkdir.test", 'w')) {
            @fclose($fp);
            @unlink("$dir/chkdir.test");
            $writeable = 1;
        } else {
            $writeable = 0;
        }
    }
    return $writeable;
}

function writable_check($path){
    $dir = '';
    $is_writable = '1';
    if(!is_dir($path)){return '0';}
    $dir = opendir($path);
    while (($file = readdir($dir)) !== false){
        if($file!='.' && $file!='..'){
            if(is_file($path.'/'.$file)){
                //是文件判断是否可写，不可写直接返回0，不向下继续
                if(!is_writable($path.'/'.$file)){
                    return '0';
                }
            }else{
                //目录，循环此函数,先判断此目录是否可写，不可写直接返回0 ，可写再判断子目录是否可写
                $dir_wrt = dir_writeable($path.'/'.$file);
                if($dir_wrt=='0'){
                    return '0';
                }
                $is_writable = writable_check($path.'/'.$file);
            }
        }
    }
    return $is_writable;
}

function set_config($config,$cfgfile) {
    $path = dir_path(APP_BASE.'../Application/Common/Conf/');
    if(!file_exists($path.$cfgfile.'.php')){
        $handle = fopen($path.$cfgfile.'.php', "w");
    }else{
        $handle = fopen($path.$cfgfile.'.php', "w");
    }
    $str = '<?php return array('."\n";
    if(is_array($config)){
        foreach($config as $k => $v){
            $str .= '\''.$k.'\'=>\''.$v.'\','."\n";
        }
    }else{

    }
    $str .= ');';
    return fwrite($handle, $str);
}

function _sql_execute($link,$sql,$r_tablepre = '',$s_tablepre = 'gtx_') {
    $sqls = _sql_split($link,$sql,$r_tablepre,$s_tablepre);
    if(is_array($sqls))
    {
        foreach($sqls as $sql)
        {
            if(trim($sql) != '')
            {
                mysqli_query($link,$sql);
            }
        }
    }
    else
    {
        mysqli_query($link,$sqls);
    }
    return true;
}

function _sql_split($link,$sql,$r_tablepre = '',$s_tablepre='gtx_') {
    global $dbcharset,$tablepre;
    $r_tablepre = $r_tablepre ? $r_tablepre : $tablepre;
    if(mysqli_get_server_info($link) > '4.1' && $dbcharset)
    {
        $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".$dbcharset,$sql);
    }

    if($r_tablepre != $s_tablepre) $sql = str_replace($s_tablepre, $r_tablepre, $sql);
    $sql = str_replace("\r", "\n", $sql);
    $ret = array();
    $num = 0;
    $queriesarray = explode(";\n", trim($sql));
    unset($sql);
    foreach($queriesarray as $query)
    {
        $ret[$num] = '';
        $queries = explode("\n", trim($query));
        $queries = array_filter($queries);
        foreach($queries as $query)
        {
            $str1 = substr($query, 0, 1);
            if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
        }
        $num++;
    }
    return $ret;
}

function create_install_lock(){
    $lock_path = HERE.'../lock.lock';
    if(!file_exists($lock_path)){
        $lock_file = fopen($lock_path, "w");
    }
}

function check_is_installed(){
    $lock_path = HERE.'../lock.lock';
    if(!file_exists($lock_path)){
        return true;
    }
    return false;
}